namespace Yaaf.WP7.NativeAccess.Provision
{
    using System;

    using Yaaf.WP7.NativeAccess.Helper;

    public interface IProvisionAccess
    {
        void Provision(string xml);
    }

    public class HtcProvisionAccess : IProvisionAccess
    {
        private ComWrapper.HTC.COM_DMXML.ProvisionXml access;

        public HtcProvisionAccess()
        {
            access = new ComWrapper.HTC.COM_DMXML.ProvisionXml();
        }

        public void Provision(string xml)
        {
            access.Provision(xml);
        }
    }

    public class LgProvisionAccess : IProvisionAccess
    {
        private ComWrapper.LG.COM_WP7STIDriver.MfgTest access;

        public LgProvisionAccess()
        {
            access = new ComWrapper.LG.COM_WP7STIDriver.MfgTest();
        }

        public void Provision(string xml)
        {
            access.ProvisionXml(xml);
        }
    }

    public class ProvisionXml : AccessManager<IProvisionAccess>
    {
        protected override IProvisionAccess GetAccessFromDevice(DeviceManufacturer manufacturer)
        {
            IProvisionAccess provisionAccess = null;
            switch (manufacturer)
            {
                case DeviceManufacturer.HTC:
                    provisionAccess = new HtcProvisionAccess();
                    break;
                case DeviceManufacturer.LG:
                    provisionAccess = new LgProvisionAccess();
                    break;
                default:
                    break;
            }
            return provisionAccess;
        }

        private static bool isInitialized = false;
        public static new void Initialize()
        {
            if (isInitialized)
            {
                return;
            }
            isInitialized = true;
            Instance = new ProvisionXml();
            Instance.Initialize();

            if (IsAvailable)
            {
                Wp7.AdvancedExplorer.Logger.Instance.WriteLine("Using following ProvisionXmlAccess: {0}, Device: {1}", Access.GetType().FullName, DeviceSwitcher.DeviceType);
            }
            else
            {
                Wp7.AdvancedExplorer.Logger.Instance.WriteLine(
                    "ProvisionXml Access not available! (Device: {0})", DeviceSwitcher.DeviceType);
            }
        }

        private static void CheckAccess()
        {
            if (!IsAvailable || Access == null)
            {
                throw new UnauthorizedAccessException("No Access on Provision Xml!");
            }
        }

        public static void Provision(string xml)
        {
            CheckAccess();
            Access.Provision(xml);
        }
    }
}